//
//  LocationManager.swift
//  WatermarkCamera
//
//  Created by 赵新 on 9/7/2024.
//

import UIKit
import RxRelay
import CoreLocation

class LocationManager: NSObject {
    /// 单例实例化
    public static let shared: LocationManager = {
        let manager = LocationManager()
        return manager
    }()

    let locationManager = CLLocationManager()
    let locatNameRelay: BehaviorRelay<String> = .init(value: "")

    var timer: Timer?

    func startLocation() {
        if AuthorizedManager.location().info.isAvailable {
            timer?.invalidate()
            timer = nil
            // 创建一个计时器对象
            timer = Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true) { [weak self] timer in
                guard let weakSelf = self else { return }
                // 获取当前位置
                if let currentLocation = weakSelf.locationManager.location {
                    let geocoder = CLGeocoder()
                    geocoder.reverseGeocodeLocation(currentLocation) { [weak self] (placemarks, error) in
                        guard let weakSelf = self else { return }
                        if let error = error {
                            print("Reverse geocoder failed with error: \(error.localizedDescription)")
                            return
                        }
                        if let placemark = placemarks?.first {
                            let address = "\(placemark.administrativeArea ?? ""), \(placemark.locality ?? ""), \(placemark.thoroughfare ?? "")"
                            weakSelf.locatNameRelay.accept(address)
                        }
                    }
                }
            }
            // 启动计时器
            timer?.fire()

        } else {
            AuthorizedManager.locationRequest()
        }
    }
}
